<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      title="黑马头条"
    >
    <van-icon
    slot="left"
    name="arrow-left"
    @click="back"
    />
    </van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{article.title}}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{article.aut_name}}</div>
          <div slot="label" class="publish-date">{{article.pubdate | relativeTime}}</div>
          <!-- 关注用户组件 -->
          <follow
          :user_id="article.aut_id"
          v-model="article.is_followed"
          />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
        class="article-content markdown-body"
        v-html="article.content"
        ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- // 文章的评论列表显示 -->
        <articleComment
        :source="this.article.art_id"
        :list="commentlist"
        @onload-success="totalCount = $event.total_count"
        @reply-click="onReplyClick"
        />
         <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="pinglun"
          >写评论</van-button>
          <van-icon
            name="comment-o"
            :info="totalCount"
            color="comment-icon"
          />
          <!-- 输入框弹出层 -->
          <van-popup
          v-model="pingisshow"
          position="bottom"
          >
          <articleList
            :target="article.art_id"
            @post-success="onPostsuccess"
          />
          </van-popup>
          <!-- 收藏 -->
          <collect
          v-model="article.is_collected"
          :userId="article.aut_id"
          />
          <!-- 点赞 -->
          <like-article
          v-model="article.attitude"
          :userId="article.art_id"
          />
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button
        class="retry-btn"
        @click="loadArtcileInfo"
        >点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 评论回复 -->
     <van-popup
       v-model="isReplyshow"
       position="bottom"
       style="height: 100%"
       >
       <!-- v-if  条件渲染  true 渲染元素节点 , false 不渲染 -->
       <CommentReplay
         v-if="isReplyshow"
         :comment="currentComent"
         @close="isReplyshow = false"
       />
      </van-popup>
    <!-- 评论回复 -->
  </div>
</template>

<script>
import { getArticleById } from '@/api/article.js'
import { ImagePreview } from 'vant'
import follow from '@/components/follow-user'
import collect from '@/components/collect-article'
import likeArticle from '@/components/like-article'
import articleComment from './components/article-comment.vue'
import articleList from './components/article-list.vue'
import CommentReplay from './components/comment-replay.vue'
// ImagePreview({
//   images: [
//     'https://img.yzcdn.cn/vant/apple-1.jpg',
//     'https://img.yzcdn.cn/vant/apple-2.jpg'
//   ],
//   // 预览图片的起始位置
//   startPosition: 0,
//   // 点击关闭
//   onClose () {
//     console.log(onClose)
//   }
// })
export default {
  name: 'ArticleIndex',
  components: {
    follow,
    collect,
    likeArticle,
    articleComment,
    articleList,
    CommentReplay
  },
  props: {
    articleId: {
      type: [Number, String],
      required: true
    }
  },
  // 给所有后代传递 inject 接受 与props 格式相同
  provide: function () {
    return {
      articleId: this.articleId
    }
  },
  data () {
    return {
      article: {}, // 文章详情
      loading: true, // 加载中的 loading 状态
      errStatus: 0, // 失败的状态码
      follwlading: false, // 加载状态
      pingisshow: false, // 评论的显示
      totalCount: 0,
      commentlist: [], // 评论列表
      isReplyshow: false,
      currentComent: {} // 点击回复评论
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadArtcileInfo()
  },
  mounted () {},
  methods: {
    back () {
      this.$router.back()
    },
    async loadArtcileInfo () {
      this.loading = true
      try {
        const { data } = await getArticleById(this.articleId)

        // 随机报错验证
        // if (Math.random() > 0.5) {
        //   JSON.parse('ddddddddddddddddd')
        // }

        this.article = data.data

        // 只有loading 为 false 才会执行下面代码,不然是 undefiend
        this.loading = false

        // 获取DOM 更新后的数据需要时间,
        this.$nextTick(() => {
          // console.log(this.$refs['article-content'])
          this.previewImage()
        })
        // 请求成功关闭loading
        // this.loading = false
      } catch (err) {
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        }
        this.$toast('数据获取失败', err)
      }
      this.loading = false
    },
    previewImage () {
      // 得到所有的 img 节点
      const articleContent = this.$refs['article-content']
      const imgs = articleContent.querySelectorAll('img')
      const images = []
      imgs.forEach((img, index) => {
        images.push(img.src)
        img.onclick = () => {
          ImagePreview({
            // 预览的图片地址数组
            images,
            // 预览图片的起始位置
            startPosition: index
          })
        }
      })
    },
    pinglun () {
      this.pingisshow = true
    },
    onPostsuccess (data) {
      // 关闭弹出层
      this.pingisshow = false
      // 将发布内容显示到列表顶部
      this.commentlist.unshift(data.new_obj)
    },
    onReplyClick (comment) {
      this.currentComent = comment
      // 显示评论显示弹出层
      this.isReplyshow = true
    }
  }
}
</script>

<style scoped lang="less">
@import './github-markdown.css';

.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
